package io.zbc.ai.spring.ai.demo.chat.client.controller;

import java.util.List;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zbc
 * @date 2025/4/23
 */
@RestController
public class ChatController {

  private final ChatClient chatClient;

  public ChatController(ChatClient.Builder clientBuilder) {
    this.chatClient = clientBuilder.build();
  }

  /**
   * 直接返回文本
   *
   * @param msg
   * @return String
   */
  @GetMapping("/chat")
  public String chat(@RequestParam("msg") String msg) {
    String content = chatClient.prompt().user(msg).call().content();
    return content;
  }

  /**
   * 包含模型输出和模型响应的元数据
   *
   * @param msg
   * @return ChatResponse
   */
  @GetMapping("/chatResponse")
  public ChatResponse chatResponse(@RequestParam("msg") String msg) {
    ChatResponse chatResponse = chatClient.prompt().user(msg).call().chatResponse();
    return chatResponse;
  }

  /**
   * 返回自定义实体类型
   *
   * @param msg
   * @return Entity
   */
  @GetMapping("/chat/returnEntity")
  public ActorFilms chatReturnEntity(@RequestParam("msg") String msg) {
    ActorFilms actorFilms = chatClient.prompt().user(msg).call().entity(ActorFilms.class);
    return actorFilms;
  }

  /**
   * 返回自定义实体类型列表
   *
   * @param msg
   * @return
   */
  @GetMapping("/chat/returnEntityList")
  public List<ActorFilms> chatReturnEntityList(@RequestParam("msg") String msg) {
    List<ActorFilms> actorFilmsList =
        chatClient
            .prompt()
            .user(msg)
            .call()
            .entity(new ParameterizedTypeReference<List<ActorFilms>>() {});
    return actorFilmsList;
  }

  record ActorFilms(String actor, List<String> movies) {}
}
